import React, {useEffect, useRef} from "react"
import {connect} from 'react-redux'
import {Card, CardBody, Button} from "reactstrap"
import Slider from "rc-slider"
import {getProjectList} from '../../../redux/actions/projects'
import {setFieldData, setData} from "../../../redux/actions/helper";

import "rc-slider/assets/index.css"
import "../../../assets/scss/plugins/extensions/slider.scss"
import FilterItem from "./FilterItem";
import {CLEAR_RELEASES_FILTER, RELEASE_SIDEBAR_HEIGHT} from "../../../redux/constants/releases";
import {getReleasesTypes} from "../../../redux/actions/releases";

const createSliderWithTooltip = Slider.createSliderWithTooltip
const Range = createSliderWithTooltip(Slider.Range)

const ReleaseSidebar = (props) => {
  const ref = useRef()

  useEffect(() => {
    if (ref && ref.current.offsetHeight)
      props.setData(RELEASE_SIDEBAR_HEIGHT, ref.current.offsetHeight + 200)
  }, [props.sidebarOpen])

  const handleShowMore = (count, type) => {
    switch (type) {
      case 'projects':
        props.getProjectList({includes: "group,owner", limit: count})
        break
      case "types":
        props.getReleasesTypes({limit: count})
        break
    }
  }

  return (
    <div ref={ref}>
      <Card>
        <CardBody className="p-2">
          <div className="multi-range-price">
            <FilterItem
              title="Проекты"
              maxValue={8}
              typeFilter="projects"
              filterData={props.projectList}
              userFilterData={props.userFilterData.projects}
              setChecked={props.setFieldData}
              showMore={handleShowMore}
            />
          </div>
          <div className="multi-range-price">
            <FilterItem
              title="Тип релиза"
              maxValue={8}
              typeFilter="types"
              filterData={props.releasesTypes}
              userFilterData={props.userFilterData.types}
              setChecked={props.setFieldData}
              showMore={handleShowMore}
            />
          </div>
          <div className="clear-filters">
            <Button.Ripple
                block
                className="btn-block"
                color="primary"
                onClick={() => props.setData(CLEAR_RELEASES_FILTER)}
              >
                Очистить фильтр
              </Button.Ripple>
          </div>
        </CardBody>
      </Card>
    </div>
  )
}

const mapStateToProps = state => ({
  releasesTypes: state.releases.releasesTypes,
  userFilterData: state.releases.userFilterData,
  projectList: {
    data: state.projects.list,
    meta: state.projects.meta
  },

})

export default connect(mapStateToProps, {
  setData,
  setFieldData,
  getProjectList,
  getReleasesTypes
})(ReleaseSidebar)
